// pages/resPackageDetailsghy/resPackageDetailsghy.js
import { createPayment } from '../../utils/payUtil';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    resPackageDishList: [],
    packageInfo: {},
    dishList: [],
    foodList: [],
    otherList: [],
    qrCodeUrl: '',
    isQrModalVisible: false, // 新增：控制二维码弹窗显示
    paymentIntervalId: null,
    paymentTimeoutId: null,
    resOrderList: [],
    userInfo: {},
    stepperValue: 1,
    totalPrice: 0,
    totalPriceYuanjia: 0
  },

  onChange(event) {
    this.setData({ 
      stepperValue: event.detail 
    },() => {
      // 在设置值后计算总价
      this.calculateTotalPrice();
    }) ;
    console.log(this.data.stepperValue);
  },

  // 计算总价
calculateTotalPrice() {
  const { respakXianjia, respakYuanjia } = this.data.packageInfo;
  const { stepperValue } = this.data;
  
  if (respakXianjia) {
    const total = parseFloat(respakXianjia) * stepperValue;
    const totalYuanjia = parseFloat(respakYuanjia) * stepperValue;
    this.setData({
      totalPrice: total.toFixed(2), // 保留两位小数
      totalPriceYuanjia: totalYuanjia.toFixed(2)
    });
  }
},

  goToResPayResultghy(){
    // this.insertResOrder();
    const resName = this.data.packageInfo.resName;
    console.log("resName", resName);
    wx.navigateTo({
      url: `/pages/resPayResultghy/resPayResultghy?resName=${encodeURIComponent(resName)}`,
    })
  },

  insertResOrder(){
    const { 
      resId, 
      validPeriod,
      respakXianjia,
      packageId,
      resName,
      respakName, 
      userId
    } = this.data.packageInfo;
    const orderTime = Date.now();
    const customerId = this.data.userInfo.userId; // 顾客Id
    const status = 0; // 支付状态,0表示待使用
    const nickName = this.data.userInfo.nickName // 顾客
    wx.request({
      url: 'http://localhost:8080/system/resorder/add',
      method: 'POST',
      data: {
        resId,
        orderTime,
        validPeriod,
        ticketCount: this.data.stepperValue,
        price: this.data.totalPrice,
        customerId,
        packageId,
        status,
        resName,
        nickName,
        packageName: respakName,
        userId
      },
      success: (res) => {
        if(res.statusCode == 200){
          console.log("订单添加成功");
        } else {
          console.error('请求失败,状态码:', res.statusCode);
        }
      },
      fail: (err) => {
        console.error('网络请求失败:', err);
      }
    })
  },

  onClickLeft(){
    wx.navigateBack();
  },

  // 显示二维码弹窗
  showQrModal(qrCodeUrl) {
    this.setData({
      qrCodeUrl,
      isQrModalVisible: true
    });
  },

  // 关闭二维码弹窗
  closeQrModal() {
    this.setData({ isQrModalVisible: false });
  },

  goPayghy() {
    // 检查用户是否登录
    const userInfo = app.globalData.userInfo;
    if (!userInfo || !userInfo.userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      wx.navigateTo({
        url: '/pages/login/login' // 如果没登录则直接跳转到登录页面
      });
      return;
    }

    const { packageInfo } = this.data;
    
    // 构造订单信息
    const orderInfo = {
      orderName: packageInfo.respakName,
      orderPrice: this.data.totalPrice,
      orderNumber: this.data.resOrderList.length + 1 // 生成唯一订单号
    };
    
    createPayment(
      orderInfo,
      (qrCodeUrl) => {
        this.setData({ qrCodeUrl });
        this.showQrModal(); // 显示自定义弹窗
      },
      (paymentStatus) => this.handlePaymentSuccess(paymentStatus),
      // 新增回调获取定时器ID
      (intervalId, timeoutId) => {
        this.setData({ paymentIntervalId: intervalId, paymentTimeoutId: timeoutId });
      }
    );
  },

  // 处理支付成功
  handlePaymentSuccess(paymentStatus) {
    console.log('支付成功状态:', paymentStatus);

    // 1. 关闭二维码弹窗
    this.closeQrModal();
    
    // 1. 插入订单记录
    this.insertResOrder();
    
    // 2. 跳转到支付结果页
    const resName = this.data.packageInfo.resName;
    wx.navigateTo({
      url: `/pages/resPayResultghy/resPayResultghy?resName=${encodeURIComponent(resName)}`,
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const baseUrl = 'http://localhost:8080';
    const packageId = options.packageId;
    console.log('接收到的 packageId:', packageId);

    // 获取用户信息
    const userInfo = app.globalData.userInfo;
    this.setData({ userInfo });
    console.log('用户信息:', userInfo);

    wx.request({
      url: 'http://localhost:8080/system/respakdish/list3',
      method: 'GET',
      data: { 
        packageId: packageId 
      },
      success: (res) => {
        if (res.statusCode === 200) {
          // 提取第一个对象中的resInfo信息
          const firstItem = res.data.data[0];
          const resInfo = firstItem.resPackage.resInfo;
          
          // 计算折扣价格
          const discount = firstItem.resPackage.discount;
          const unitPrice = firstItem.resPackage.unitPrice;
          const discountedPrice = (unitPrice * (discount / 10)).toFixed(2);

          // 筛选菜品分类
          const dishList = res.data.data.filter(item => 
            item.resDish && item.resDish.dishCategoryId == 1001
          );
          
          const foodList = res.data.data.filter(item => 
            item.resDish && item.resDish.dishCategoryId == 1002
          );
          
          const otherList = res.data.data.filter(item => 
            item.resDish && item.resDish.dishCategoryId == 1003
          );
          
          // 设置套餐信息
          this.setData({
            resPackageDishList: res.data.data,
            dishList: dishList,
            foodList: foodList,
            otherList: otherList,
            packageInfo: {
              packageId: firstItem.resPackage.packageId, //套餐Id
              resName: resInfo.resName, // 餐厅名称
              respakName: firstItem.resPackage.packageName, // 套餐名称
              imageUrl: baseUrl + firstItem.resPackage.imgUrl, // 套餐图片
              respakXianjia: discountedPrice, // 现价
              respakYuanjia: unitPrice, // 原价
              respakDiscount: discount, // 折扣
              validPeriod: firstItem.resPackage.validPeriod, // 有效期
              resId: firstItem.resPackage.resId, // 餐馆Id
              userId: firstItem.resPackage.resInfo.userId // 注意,该userId是餐馆所属人的userId
            }
          }, () => {
            // 数据设置完成后计算初始总价
            this.calculateTotalPrice();
          });
          console.log('packageInfo:', this.data.packageInfo);
          console.log('套餐菜品列表数据:', this.data.resPackageDishList);
          console.log('菜品列表:', dishList);
          console.log('主食列表:', foodList);
          console.log('其他列表:', otherList);
        }
      },
      fail: (err) => {
        console.error('请求出错:', err);
      }
    });

    // 调用后端接口获取订单列表数据
    wx.request({
      url: 'http://localhost:8080/system/resorder/list1',
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            resOrderList: res.data.rows // 假设返回的数据结构中订单列表在 data 字段中
          });
          console.log('订单列表数据:', this.data.resOrderList);
        }
      },
      fail: (err) => {
        console.error('请求出错:', err);
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 在页面卸载时清除定时器
    const { paymentIntervalId, paymentTimeoutId } = this.data;
    if (paymentIntervalId) clearInterval(paymentIntervalId);
    if (paymentTimeoutId) clearTimeout(paymentTimeoutId);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})